home *** CD-ROM | disk | FTP | other *** search
- Path: news.cais.com!news
- From: Lally Singh <lsingh@ids2.idsonline.com>
- Newsgroups: comp.lang.c++
- Subject: Re: HELP Borland C++ 5.0 pointer problem
- Date: Tue, 16 Apr 1996 16:58:04 -0400
- Organization: Capital Area Internet Service info@cais.com 703-448-4470
- Message-ID: <317409DC.59B@ids2.idsonline.com>
- References: <4klke8$7mb@dub-news-svc-2.compuserve.com> <316e9fdb.457757@10.0.2.1>
- NNTP-Posting-Host: ip190.idsonline.com
- Mime-Version: 1.0
- Content-Type: text/plain; charset=us-ascii
- Content-Transfer-Encoding: 7bit
- X-Mailer: Mozilla 2.0 (Win95; I)
-
- Adam Gensler wrote:
- > That won't work because when you leave the function the memeory reserved for
- > buffer[20] is marked as free. ^^^^- almost, actually, it's created in the stack.
- > >Could you please tell me why the function below compiles and operates
- > >correctly under win16 but not win32 ?
-
- > > char* test_function(char *in_data) {
- > >
- > > char buffer[20];
- > > strcpy(buffer, in_data); // copy in_data to buffer
- > > in_data = buffer; // set pointer to buffer
- > >
- > > return(in_data);
- > >
- > > } // end test_function function
-
- Mr. Gensler is correct in that the buffer is not available after the function
- ends, but it is not marked free, it was never in the heap, rather in the stack.
- When the function returns, the stack is cleaned up and then the next time something
- is pushed or popped, then that data is overwritten.
- If under Win32 you get garbage, then that is what's happening. If you get something
- like a general protection fault, then the fault is from an attempt to access a
- memory address beyond the range of the stack (meaning that the stack pointer has been
- moved back before the place where it was when the buffer was allocated) and thus
- you're trying to get an invalid address, which Win32 I know doesn't like too much.
-
- To fix it, you have to do something like this:
-
- char * testfunction( char * inData)
- {
- char * buffer = new[] char[20]; // allocates on the heap, remember to delete[] it!
- strcpy( buffer, inData ); // copy the string
- return buffer; // return the new buffer
- };
-